package com.girant.service.Result;
import com.girant.DTO.SearchResultDTO;
import cn.hutool.core.bean.BeanUtil;
import com.girant.entity.Material;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.search.SearchHit;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class DefineResult{
    public SearchResultDTO<Material> process(List<SearchHit> filteredHits, int size, long currentHits, Object[] nextSearchAfter, long took){
        SearchResultDTO<Material> result = new SearchResultDTO<>();
        List<Material> pageData = new ArrayList<>();
        // 遍历结果，转换为Material对象
        for (SearchHit hit : filteredHits) {
            Map<String, Object> sourceMap = hit.getSourceAsMap();
            pageData.add(mapToMaterial(sourceMap, hit.getScore()));
        }
        // 判断是否有下一页：当前页满了 且 总命中数大于已返回的数量（含当前页）
        boolean hasNext = nextSearchAfter != null && currentHits >= size;  //过滤后可能小于size，但锚点存在说明有更多数据

        // 封装结果
        result.setTotal(currentHits);
        result.setSize(size);
        result.setTook(took);  // 从主查询中传递的耗时
        result.setData(pageData);
        result.setHasNext(hasNext);
        result.setNextSearchAfter(hasNext ? nextSearchAfter : null);
        return result;
    }

    private Material mapToMaterial(Map<String, Object> sourceMap, float score) {
        Material material = new Material();
        // 类型转换增强容错性（避免空指针或类型不匹配）
        Material DTO = BeanUtil.copyProperties(material, Material.class);
        material.setId(convertToString(sourceMap.get("id")));
        material.setScore(score);
        material.setMaterialType((String) sourceMap.get("material_type"));
        material.setMaterialName((String) sourceMap.get("material_name"));
        material.setMaterialAlias((String) sourceMap.get("material_alias"));
        material.setMaterialAttribute((String) sourceMap.get("material_attribute"));
        material.setMaterialCategory((String) sourceMap.get("material_category"));
        material.setMaterialCode((String) sourceMap.get("material_code"));
        material.setMaterialSpecs((String) sourceMap.get("material_specs"));
        material.setBaseUnit((String) sourceMap.get("base_unit"));
        return material;
    }
    private String convertToString(Object value) {
        if (value == null) {
            return null;
        }
        return value.toString();  // 数字、布尔等类型直接转字符串
    }
}
